const express = require('express');
const router = express.Router();
const deepseek = require('../module/deepseek/index')
const OpenAI = require('openai')

const openaiRole = new OpenAI({
    baseURL: 'https://api.deepseek.com',
    apiKey: 'sk-96f82303288c450a8f847d5b2edf257a'
});

/* GET users listing. */
router.post('/deepseek', async (req, res, next) => {
    try {
        // 设置流式响应头
        res.setHeader('Content-Type', 'text/plain');
        res.setHeader('Transfer-Encoding', 'chunked');
        console.log(req.body.messages)
        const completion = await openaiRole.chat.completions.create({
            messages: req.body.messages,
            stream: true,
            model: "deepseek-chat",
        });
        console.log(completion);
        // 逐块流式回传
        for await (const chunk of completion) {
            const content = chunk.choices[0]?.delta?.content || '';
            // console.log(content)
            res.write(content); // 关键：使用 write 而非 json
        }

        // 结束响应
        res.end();
    } catch (error) {
        console.error('Stream error:', error);
        res.status(500).json({ code: 500, msg: 'Stream failed' });
    }
});

router.post('/deepseekNotStream', async (req, res, next) => {
    try {
        // 设置流式响应头
        res.setHeader('Content-Type', 'text/plain');
        res.setHeader('Transfer-Encoding', 'chunked');
        console.log(req.body.messages)
        const completion = await openaiRole.chat.completions.create({
            // messages: req.body.messages,
            messages: [{
                role: 'user',
                content: `帮我规划一条广州的路线，以 [ { name: '', latitude: '', longitude: '' } ] 的方式返回`
            }],
            stream: false,
            model: "deepseek-chat",
        });
        console.log(completion);
        res.json({
            code: 200,
            msg: 'success',
            data: completion
        });
    } catch (error) {
        console.error('Stream error:', error);
        res.status(500).json({ code: 500, msg: 'Stream failed' });
    }
});


module.exports = router;
